#include<unistd.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<signal.h>

typedef struct mymem{
    int id;
    char name[10];
    int age;
}mymem;

int shidentify;
mymem* mems;
void handle_error(const char * info){
    perror(info);
    exit(0);
}

typedef void (*sighandler_t)(int);

void remove_shm(int signo){
    printf("detach the shm: %p\n", mems);
    if (shmdt(mems) == -1) handle_error("shmdt");
    if (shmctl(shidentify, IPC_RMID, 0) == -1) handle_error("shmctl");
    exit(0);  
}
int main()
{
    // 创造信号处理
    signal(SIGINT, remove_shm);
    if( (shidentify = shmget((key_t)0x5005, sizeof(mymem)*10, 0644 | IPC_CREAT)) == -1){
        handle_error("shmget");
    }     

    mems = (mymem *)shmat(shidentify, NULL, 0);
    if(mems == (void *) -1) handle_error("shmat");
    
    for(int i = 0; i< 10; i++)
    {
        char name[20];
        mems[i].id = i;
        mems[i].age = i+10;
        sprintf(mems[i].name, "stu%d", mems[i].id);
    }

    while(1);
    
}